package com.example.websocketpoint2point.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.AbstractPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * spring security 配置
 * @author ljw
 * @description
 * @date 2022/4/8 7:04
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置拦截路径和跳转路径
     * @param
     * @author ljw
     * @date 2022/4/8 7:10
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/login").permitAll() //对 / 和 /login 路径不拦截
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")    //登录页面访问路径为 /login
                .defaultSuccessUrl("/chat") //  登录成功后跳转 /chat 路径
                .permitAll()
                .and()
                .logout()
                .permitAll();

    }

    /**
     * 配置登录认证
     * @param
     * @author ljw
     * @date 2022/4/8 7:11
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //内存中配置两个用户wyf 和 wisely ,密码和用户名一样，角色是 USER
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder())
                .withUser("wyf").password("wyf").roles("USER")
                .and()
                .withUser("wisely").password("wisely").roles("USER");
    }

    /**
     * 配置静态资源
     * @param
     * @author ljw
     * @date 2022/4/8 7:11
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //不拦截对应路径静态资源
        web.ignoring().antMatchers("/resources/static/**");
    }

    class MyPasswordEncoder implements PasswordEncoder {

        @Override
        public String encode(CharSequence rawPassword) {
            return rawPassword.toString();
        }

        @Override
        public boolean matches(CharSequence rawPassword, String encodedPassword) {
            return encodedPassword.equals(rawPassword.toString());
        }
    }
}
